<template>
  <div class="app-container">
    <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
      :model="formData" :rules="rules" size="medium" label-width="120px">
      <h2 style="text-align: center">设备校准结果确认</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8" v-if="$route.query.isEdit || $route.query.isInfo || isInfo">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input disabled v-model="formData.deviceName" placeholder="请输入设备名称" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-else>
          <el-form-item label="设备名称" prop="deviceCheckCertId">
            <!-- <el-select v-if="!($route.query.isInfo || isInfo)" filterable v-model="formData.deviceCheckCertId"
              placeholder="请选择设备名称" clearable @change="changeDevice" :style="{ width: '100%' }">
              <el-option v-for="(item, index) in deviceOptions" :key="index" :label="item.deviceVo.deviceName"
                :value="item.deviceCheckCertId">
                <span style="float: left">{{ item.deviceVo.deviceName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{
                    item.deviceCode
                  }}
                </span>
              </el-option>
            </el-select>
            <el-input disabled v-else v-model="formData.deviceName" placeholder="请输入设备名称" clearable
              :style="{ width: '100%' }"></el-input> -->
            <div style="display: flex;">
              <el-select :disabled="$route.query.isEdit" filterable v-model="formData.deviceCheckCertId"
                placeholder="请选择设备名称" clearable @change="changeDevice" :style="{ width: '100%' }"
                :filter-method="changeInput">
                <el-option v-for="(item, index) in deviceOptions" :key="index" :label="item.deviceName"
                  :value="item.deviceCheckCertId" :disabled="item.disabled">
                  <span style="float: left">{{ item.deviceName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.deviceCode
                  }}</span>
                </el-option>
              </el-select>
              <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" size="mini" @click="sousuo">查询</el-button>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input disabled v-model="formData.deviceCode" placeholder="请输入设备编号" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备用途" prop="useInfo">
            <el-input disabled v-model="formData.useInfo" placeholder="请输入设备用途" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保管部门" prop="deptId">
            <el-cascader disabled :props="{ value: 'id', checkStrictly: true }" :show-all-levels="false" ref="reference"
              placeholder="请选择保管部门" :style="{ width: '100%' }" v-model="formData.deptId"
              :options="deptOptions"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检定/校准单位" prop="organ">
            <el-select v-model="formData.organ" placeholder="请选择检定/校准单位" clearable :disabled="true"
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.sys_organ_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检定/校准周期" prop="checkPeriod">
            <el-input disabled v-model="formData.checkPeriod" placeholder="请输入检定/校准周期" clearable
              :style="{ width: '100%' }">
              <template slot="append">个月</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="设备类型" prop="deviceTypeValue">
            <el-select v-model="formData.deviceTypeValue" placeholder="请选择设备类型" clearable :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书/报告性质" prop="type">
            <el-select disabled v-model="formData.deviceCheckCertVo.type" placeholder="请选择证书/报告性质" clearable
              :style="{ width: '100%' }">
              <el-option v-for="dict in dict.type.sys_device_cert_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="证书/报告编号" prop="code">
            <el-input disabled v-model="formData.code" placeholder="请输入证书/报告编号" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="formData.deviceTypeValue != 2">
          <el-form-item label="分设备编号范围" prop="codeRange">
            <el-input v-model="formData.codeRange" placeholder="请输入分设备编号范围" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="查看证书" prop="codeRange">
            <FileUploadBase :isShowTip="false" :isDelete="false" v-model="formData.oss"></FileUploadBase>
          </el-form-item>
        </el-col>
      </el-row>

      <h4 class="form-header h4">确认内容</h4>
      <el-form-item prop="confirmAppearance">
        <el-checkbox-group v-model="content">
          <el-checkbox :key="item" v-for="item in dict.type.sys_device_cert_content" :label="item.value">
            {{ item.label
            }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <h4 class="form-header h4">根据证书、报告内容可确定</h4>
      <el-form-item prop="confirmAppearance">
        <el-radio-group v-model="itemList">
          <div style="margin-top: 10px" v-for="item in dict.type.sys_device_content_confrim">
            <el-radio :label="item.value" v-if="item.value == 1">
              <span v-for="(i, e) in item.label.split('###')">
                {{ i }}
                <el-input v-if="e == 0" type="textarea" v-model="param1" clearable :style="{ width: '600px' }"></el-input>
              </span>
            </el-radio>
            <el-radio :label="item.value" v-else>{{ item.label }}</el-radio>
          </div>
        </el-radio-group>
      </el-form-item>
      <!-- <el-row gutter="15">
        <el-col :span="8">
          <el-form-item label="参数1"> </el-form-item>
        </el-col>
      </el-row>-->
      <h4 class="form-header h4">
        数据确认
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button>
      </h4>
      <el-table :data="formData.projectList" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="检测项目" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`projectList.${scope.$index}.projectName`" :rules="rules.projectName">
              <el-input v-model="scope.row.projectName" placeholder="请输入检测项目"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="测试结果" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`projectList.${scope.$index}.result`" :rules="rules.result">
              <el-input v-model="scope.row.result" placeholder="请输入测试结果"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="要求(无相应标准、规范、规程要求的参照公司规定)" align="center">
          <el-table-column label="标准、规范、规程要求" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`projectList.${scope.$index}.request`" :rules="rules.request">
                <el-input v-model="scope.row.request" placeholder="请输入标准、规范、规程要求"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="公司规定" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`projectList.${scope.$index}.companyRequest`"
                :rules="rules.companyRequest">
                <el-input v-model="scope.row.companyRequest" placeholder="请输入公司规定"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <el-col :span="8" style="margin-top: 20px;">
        <el-form-item label="确认日期" prop="confirmTime" label-width="80px">
          <el-date-picker v-model="formData.confirmTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{ width: '100%' }" placeholder="请选择确认日期" clearable></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="formData.confirmTime" style="margin-top: 20px;">
        <el-form-item label="上级审批日期" prop="time">
          <el-date-picker v-model="formData.confirmTime" :disabled="true" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }"
            placeholder="暂无上级审批时间" clearable></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="btnShow">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(1)">提交</el-button>
          <el-button v-if="!($route.query.isInfo || isInfo) && (formData.status == 'draft' || !formData.status)"
            type="primary" @click="submitForm(0)">暂存</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <el-dialog title="查看证书" :visible.sync="dialogTableVisible">
      <div>
        <img src alt />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  resultConfirmAdd,
  updategresultConfirm,
  resultConfirmInfo
} from "@/api/device/resultConfirm.js";
import { deptTreeSelect } from "@/api/system/user.js";
import { listSelectChey } from "@/api/device/device.js";
import { listSelect } from "@/api/device/device.js";
import { selectListDeviceCheckCert } from "@/api/device/deviceCheckCert.js";
export default {
  components: {},
  dicts: [
    "sys_device_type",
    "sys_device_cert_type",
    "sys_device_cert_content",
    "sys_device_content_confrim",
    "sys_organ_type"
  ],

  props: {
    isInfo: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ""
    },
    btnShow: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      param1: "",
      content: [],
      itemList: [],
      deviceOptions: [],
      carSelectList: [],
      checkImage: "",
      formData: {
        contentList: [],
        itemList: [],
        projectList: [
          { projectName: "", result: "", request: "", companyRequest: "" }
        ],
        deviceCheckCertVo: {},
        deviceCode: undefined,
        organ: undefined,
        checkPeriod: undefined,
        deviceTypeValue: undefined,
        codeRange: undefined,
        deviceCheckCertId: undefined,
        useInfo: undefined,
        deptId: undefined,
        certTypeValue: undefined,
        code: undefined
      },
      dialogTableVisible: false,
      rules: {
        checkPeriod: [
          {
            required: true,
            message: "请选择日期",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: false,
            message: "请输入证书/报告编号",
            trigger: "blur"
          }
        ],
        projectName: [
          {
            required: true,
            message: "请输入检测项目",
            trigger: "blur"
          }
        ],
        result: [
          {
            required: true,
            message: "请输入测试结果",
            trigger: "blur"
          }
        ],
        request: [
          {
            required: true,
            message: "请输入标准、规范、规程要求",
            trigger: "blur"
          }
        ],
        companyRequest: [
          {
            required: true,
            message: "请输入公司规定",
            trigger: "blur"
          }
        ],
        deviceCheckCertId: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: "blur"
          }
        ],
        codeRange: [
          {
            required: false,
            message: "分设备编号范围",
            trigger: "blur"
          }
        ],
        deviceTypeValue: [
          {
            required: true,
            message: "请选择设备类型",
            trigger: "blur"
          }
        ],
        useInfo: [
          {
            required: true,
            message: "请输入主要用途",
            trigger: "blur"
          }
        ],
        organ: [
          {
            required: false,
            message: "请输入请输入检定/校准单位",
            trigger: "blur"
          }
        ],
        deviceCode: [
          {
            required: true,
            message: "请输入设备编号",
            trigger: "change"
          }
        ],
        deptId: [
          {
            required: true,
            message: "请选择保管部门",
            trigger: "change"
          }
        ],
        certTypeValue: [
          {
            required: true,
            message: "请选择证书/报告性质",
            trigger: "change"
          }
        ]
      },
      supplierIdOptions: [],
      deptOptions: [],
      flag: '',
      keyword: ''
    };
  },
  computed: {},
  created() {
    this.selectList();
    this.getDeptTree();
    console.log(this.$route.query.isInfo);
    this.$route.query.isInfo = (this.$route.query.isInfo == 'false' || this.$route.query.isInfo == false) ? false : this.$route.query.isInfo
    if (
      this.$route.query.isEdit ||
      this.$route.query.isInfo ||
      this.isInfo ||
      this.$route.query.isClone
    ) {
      this.getinfo();
    }
    this.flag = this.$route.query.flag
  },
  mounted() { },
  methods: {
    changeInput(e) {
      console.log(e);
      this.keyword = e
    },
    sousuo() {
      selectListDeviceCheckCert({
        managerUserId: this.$store.state.user.id,
        keyword: this.keyword
      }).then(response => {
        this.deviceOptions = response.data;
      });
    },
    handleAdd() {
      this.formData.projectList.push({
        projectName: "",
        result: "",
        request: "",
        companyRequest: ""
      });
    },
    handleDele() {
      if (this.formData.projectList.length == 1) return;
      this.formData.projectList.pop();
    },
    changeDevice(i) {
      let row = this.deviceOptions.find(e => e.deviceCheckCertId == i);
      console.log(row);
      if (row) {
        console.log(row);
        this.formData.checkPeriod = row.deviceVo.checkPeriod;
        this.formData.checkCertId = row.deviceCheckCertId;
        this.formData.deviceId = row.deviceId;
        this.formData.deviceCode = row.deviceCode;
        this.formData.code = row.certCode;
        this.formData.organ = row.organ;
        this.formData.useInfo = row.deviceVo.useInfo;
        this.formData.deptId = row.deviceVo.deptId;
        this.formData.deptName = row.deviceVo.deptName;
        this.formData.deviceName = row.deviceVo.deviceName;
        this.formData.deviceCheckCertVo.type = row.type;
        this.formData.type =  row.type
        this.formData.oss = row.oss;
      } else {
        this.formData.deviceCode = undefined;
        this.formData.deviceName = undefined;
        this.formData.checkPeriod = undefined;
        this.formData.code = undefined;
        this.formData.type = undefined;
        this.formData.useInfo = undefined;
        this.formData.deptId = undefined;
        this.formData.deptName = undefined;
        console.log(this.formData.type);
      }
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    selectList() {
      selectListDeviceCheckCert({
        managerUserId: this.$store.state.user.id
      }).then(response => {
        this.deviceOptions = response.data;
      });
    },

    getinfo() {
      return resultConfirmInfo(this.$route.query.id || this.id).then(
        response => {
          this.formData = response.data;
          this.formData.deviceCheckCertId = this.formData.checkCertId;
          this.formData.oss = response.data.deviceCheckCertVo.oss;
          this.content = this.formData.contentList
            .filter(i => i.isSelected == 0)
            .map(e => e.contentValue);
          this.itemList = this.formData.itemList
            .filter(i => i.isSelected == 0)
            .map(e => e.contentValue)
            .toString();
          this.formData.itemList.forEach(e => {
            if (e.contentValue == 1) {
              this.param1 = e.param1;
            }
          });
          if (this.$route.query.isClone) {
            //colne
            this.formData.deviceId = undefined;
            this.formData.deviceResultConfirmId = undefined;
            this.formData.deviceCheckCertId = undefined;
            this.changeDevice(null);
            this.formData.projectList = this.formData.projectList.map(item => ({ ...item, ['deviceResultConfirmProjectId']: '' }))
            this.formData.itemList = this.formData.itemList.map(item => ({ ...item, ['deviceResultConfirmContentId']: '' }))
            this.formData.contentList = this.formData.contentList.map(item => ({ ...item, ['deviceResultConfirmContentId']: '' }))
          }
          console.log(this.formData);
          this.formData.time = this.formData.wfDetailVo.historyProcNodeList[1].commentList[0].time;
          console.log(this.formData, "/");
          // if(this.$route.query.) {
        }
      );
    },

    submitForm(e) {
      console.log(this.itemList);
      if (this.itemList.includes("1") && !this.param1) {
        this.$message.warning("请输入功能");
        return;
      }
      let query = JSON.parse(JSON.stringify(this.formData));
      if (this.formData.contentList && this.formData.contentList.length) {
        // 是编辑的
        query.contentList.forEach(i => {
          i.isSelected = this.content.includes(i.contentValue) ? 0 : 1;
        });
      } else {
        // 新增
        let list = this.dict.type.sys_device_cert_content.map(i => {
          return {
            isSelected: this.content.includes(i.value) ? 0 : 1,
            contentValue: i.value,
            contentLabel: i.label
          };
        });
        console.log(list);
        query.contentList = list;
      }

      // 根据证书、报告内容可确定
      if (this.formData.itemList && this.formData.itemList.length) {
        // 是编辑的
        query.itemList.forEach(i => {
          console.log(this.itemList, i.contentValue);
          i.isSelected = this.itemList == i.contentValue ? 0 : 1;
          // if (this.itemList == 1 && !i.isSelected) {
          if (this.itemList == i.contentValue) {
            console.log(i.isSelected);
            // console.log(i.);
            console.log(this.param1, '编辑', i.contentValue);
            //选择了可输入的
            i.param1 = this.param1;
          }
        });
      } else {
        // 新增
        let list = this.dict.type.sys_device_content_confrim.map(i => {
          return {
            isSelected: this.itemList == i.value ? 0 : 1,
            contentValue: i.value,
            contentLabel: i.label,
            param1: this.param1
          };
        });
        query.itemList = list;
      }
      if (query.type) {
        query.certTypeLabel = this.dict.type.sys_device_cert_type.find(
          i => i.value === query.type
        ).label;
        query.certTypeValue = query.type;
      }
      
      if (query.status != 'end') {
        query.status = e == 0 ? 'draft' : 'audit'
      }
      if (this.flag == '克隆') {
        query.status = 'audit'
        query.pid = ''
      }
      console.log(query.status, "query.status ");
      //暂存 不走校验
      if (e == 0) {
        if (!this.formData.checkCertId) {
          this.$message.warning("请先选择设备名称");
          return;
        }
        query.status = "draft"
        if (this.formData.deviceResultConfirmId != undefined) {
            updategresultConfirm(query).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            resultConfirmAdd(query).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        return;
      }
      console.log(query);
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          query.deptId = this.$refs.reference.getCheckedNodes()[0].value;
          query.deptName = this.$refs.reference.getCheckedNodes()[0].label;
          if (this.formData.deviceResultConfirmId != undefined) {
            updategresultConfirm(query).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            resultConfirmAdd(query).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    }
  }
};
</script>
